<template>
    <div class="statistics-container">
      <el-row :gutter="20">
        <!-- 年龄分布图 -->
        <el-col :span="8">
          <div id="age-distribution" style="height: 350px;"></div>
        </el-col>
        <!-- 职称分布图 -->
        <el-col :span="8">
          <div id="title-distribution" style="height: 350px;"></div>
        </el-col>
        <!-- 所在系分布图 -->
        <el-col :span="8">
          <div id="department-distribution" style="height: 350px;"></div>
        </el-col>
      </el-row>
      <!-- 更多图表，可以在新的一行展示 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <div id="age-pie" style="height: 350px;"></div>
        </el-col>
        <el-col :span="12">
          <div id="department-pie" style="height: 350px;"></div>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import { listInfoAll } from "@/api/teacher/info/info";
  
  export default {
    name: "Statistics",
    data() {
      return {
        infoList: [],
        ageData: [],
        titleData: [],
        departmentData: []
      };
    },
    created() {
      this.getList();
    },
    mounted() {
      this.$nextTick(() => {
        this.getList(); // 加载数据后初始化图表
      });
    },
    methods: {
      /** 获取教师数据并处理统计数据 */
      getList() {
        listInfoAll().then(response => {
          console.log("Response from server:", response);
          this.infoList = response.rows;
  
          if (this.infoList && this.infoList.length > 0) {
            this.processStatisticsData(); // 处理统计数据
            this.initCharts(); // 数据加载完成后再初始化图表
          } else {
            console.warn("No data available for charts.");
            this.showEmptyCharts();
          }
        }).catch(error => {
          console.error("Error fetching data:", error);
        });
      },
  
      /** 处理年龄、职称和所在系的统计数据 */
      processStatisticsData() {
        this.ageData = this.calculateAgeDistribution();
        this.titleData = this.calculateTitleDistribution();
        this.departmentData = this.calculateDepartmentDistribution();
      },
  
      /** 计算年龄分布 */
      calculateAgeDistribution() {
        const ageGroups = { '20-30': 0, '31-40': 0, '41-50': 0, '51-60': 0, '61+': 0 };
        this.infoList.forEach(item => {
          const age = item.age;
          if (age >= 20 && age <= 30) ageGroups['20-30']++;
          else if (age >= 31 && age <= 40) ageGroups['31-40']++;
          else if (age >= 41 && age <= 50) ageGroups['41-50']++;
          else if (age >= 51 && age <= 60) ageGroups['51-60']++;
          else ageGroups['61+']++;
        });
        return Object.keys(ageGroups).map(key => ({ name: key, value: ageGroups[key] }));
      },
  
      /** 计算职称分布 */
      calculateTitleDistribution() {
        const titleGroups = {};
        this.infoList.forEach(item => {
          const title = item.title || "未知";
          titleGroups[title] = (titleGroups[title] || 0) + 1;
        });
        return Object.keys(titleGroups).map(title => ({ name: title, value: titleGroups[title] }));
      },
  
      /** 计算所在系分布 */
      calculateDepartmentDistribution() {
        const departmentGroups = {};
        this.infoList.forEach(item => {
          const department = item.department || "未知";
          departmentGroups[department] = (departmentGroups[department] || 0) + 1;
        });
        return Object.keys(departmentGroups).map(department => ({ name: department, value: departmentGroups[department] }));
      },
  
      /** 初始化所有图表 */
      initCharts() {
        if (this.ageData && this.ageData.length > 0) {
          this.initAgeChart();
          this.initAgePieChart();
        }
  
        if (this.titleData && this.titleData.length > 0) {
          this.initTitleChart();
        }
  
        if (this.departmentData && this.departmentData.length > 0) {
          this.initDepartmentChart();
          this.initDepartmentPieChart();
        }
      },
  
      /** 初始化年龄分布图（柱状图） */
      initAgeChart() {
        const ageChart = echarts.init(document.getElementById("age-distribution"));
        const ageOption = {
          title: { text: '教师年龄分布', left: 'center', textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' } },
          tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
          xAxis: { type: 'category', data: this.ageData.map(item => item.name), axisLabel: { textStyle: { color: '#666' } } },
          yAxis: { type: 'value', axisLabel: { textStyle: { color: '#666' } } },
          series: [{
            data: this.ageData.map(item => item.value),
            type: 'bar',
            itemStyle: { color: '#42a5f5' },
            barWidth: '40%',
            animationDuration: 1500,
          }],
          grid: { top: '20%', bottom: '20%' }
        };
        ageChart.setOption(ageOption);
      },
  
      /** 初始化职称分布图（雷达图） */
    //   initTitleChart() {
    //     const titleChart = echarts.init(document.getElementById("title-distribution"));
    //     const titleOption = {
    //       title: { text: '教师职称分布', left: 'center', textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' } },
    //       tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
    //       radar: {
    //         indicator: this.titleData.map(item => ({ name: item.name, max: 10 }))
    //       },
    //       series: [{
    //         name: '职称分布',
    //         type: 'radar',
    //         data: [{
    //           value: this.titleData.map(item => item.value),
    //           name: '职称'
    //         }],
    //         itemStyle: { color: '#66bb6a' },
    //         animationDuration: 1500,
    //       }]
    //     };
    //     titleChart.setOption(titleOption);
    //   },
    initTitleChart() {
        // 获取目标DOM元素
        const titleChart = echarts.init(document.getElementById("title-distribution"));
        
        // 获取总人数（假设为 titleData 中所有人数的总和）
        const totalCount = this.titleData.reduce((sum, item) => sum + item.value, 0);
        
        // 配置项
        const titleOption = {
            title: {
                text: '教师职称分布',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'item',  // 当鼠标悬停在图形上时触发显示
                formatter: (params) => {
                    // 格式化提示框显示的内容，转换为百分比
                    const percentage = ((params.value / totalCount) * 100).toFixed(2);
                    return `${params.name}: ${params.value} 人 (${percentage}%)`;
                }
            },
            series: [{
                name: '职称分布',
                type: 'pie',  // 饼图类型
                radius: ['40%', '70%'],  // 环形图的内外半径
                data: this.titleData.map(item => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: {
                        color: '#66bb6a'  // 数据项的颜色
                    }
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'  // 鼠标悬停时的效果
                    }
                }
            }]
        };

        // 渲染图表
        titleChart.setOption(titleOption);

        // 如果窗口大小发生变化，则调整图表大小
        window.addEventListener("resize", function () {
            titleChart.resize();
        });
    }
    ,
    
  
      /** 初始化所在系分布图（饼图） */
      initDepartmentChart() {
        const departmentChart = echarts.init(document.getElementById("department-distribution"));
        const departmentOption = {
          title: { text: '教师所在系分布', left: 'center', textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' } },
          tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
          series: [{
            name: '系分布',
            type: 'pie',
            radius: '50%',
            data: this.departmentData.map(item => ({ name: item.name, value: item.value })),
            itemStyle: {
              normal: {
                color: function(params) {
                  const colors = ['#ff7043', '#42a5f5', '#66bb6a', '#ffeb3b'];
                  return colors[params.dataIndex % colors.length];
                }
              }
            },
            animationDuration: 1500,
          }]
        };
        departmentChart.setOption(departmentOption);
      },
  
      /** 初始化年龄分布的饼图 */
      initAgePieChart() {
        const agePieChart = echarts.init(document.getElementById("age-pie"));
        const agePieOption = {
          title: { text: '教师年龄比例', left: 'center', textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' } },
          tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
          series: [{
            name: '年龄分布',
            type: 'pie',
            radius: '50%',
            data: this.ageData.map(item => ({ name: item.name, value: item.value })),
            itemStyle: {
              normal: {
                color: function(params) {
                  const colors = ['#42a5f5', '#66bb6a', '#ff7043', '#ffeb3b'];
                  return colors[params.dataIndex % colors.length];
                }
              }
            },
            animationDuration: 1500,
          }]
        };
        agePieChart.setOption(agePieOption);
      },
  
      /** 初始化所在系分布的饼图 */
    //   initDepartmentPieChart() {
    //     const departmentPieChart = echarts.init(document.getElementById("department-pie"));
    //     const departmentPieOption = {
    //         title: { text: '教师所在系比例', left: 'center', textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' } },
    //     tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
    //     series: [{
    //       name: '系分布',
    //       type: 'pie',
    //       radius: '50%',
    //       data: this.departmentData.map(item => ({ name: item.name, value: item.value })),
    //       itemStyle: {
    //         normal: {
    //           color: function(params) {
    //             const colors = ['#ff7043', '#42a5f5', '#66bb6a', '#ffeb3b'];
    //             return colors[params.dataIndex % colors.length];
    //           }
    //         }
    //       },
    //       animationDuration: 1500,
    //     }]
    //   };
    //   departmentPieChart.setOption(departmentPieOption);
    // },
    initDepartmentPieChart() {
        const departmentScatterChart = echarts.init(document.getElementById("department-pie"));
        const departmentScatterOption = {
            title: { 
                text: '教师所在系比例',
                left: 'center',
                textStyle: { fontSize: 18, fontWeight: 'bold', color: '#333' }
            },
            tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
            xAxis: {
                type: 'category',
                data: this.departmentData.map(item => item.name),
                axisLabel: { rotate: 45, fontSize: 12 }
            },
            yAxis: {
                type: 'value',
                axisLabel: { fontSize: 12 }
            },
            series: [{
                name: '系分布',
                type: 'scatter',
                data: this.departmentData.map((item, index) => [index, item.value]),
                itemStyle: { color: '#66bb6a' },
                symbolSize: 15,
                animationDuration: 1500,
            }]
        };
        departmentScatterChart.setOption(departmentScatterOption);
    },


        /** 显示空的图表 */
        showEmptyCharts() {
        // 在数据为空时，显示空的图表
        this.initAgeChart();
        this.initTitleChart();
        this.initDepartmentChart();
        this.initAgePieChart();
        this.initDepartmentPieChart();
        }
    }
    };
</script>

<style scoped>
.statistics-container {
  padding: 20px;
  background-color: #f7f7f7;
  border-radius: 8px;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  padding: 10px;
}

.el-row > .el-col {
  border-radius: 8px;
  background-color: #fff;
}

.el-row > .el-col:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-col .chart-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.el-row + .el-row {
  margin-top: 30px;
}
</style>

  